package dtd.PHS.VND_ExchangeRate;

import java.io.IOException;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import dtd.PHS.VND_ExchangeRate.data.VCBRatesParser;
import dtd.PHS.VND_ExchangeRate.data.VNExDatabase;
import dtd.PHS.VND_ExchangeRate.utils.ApplicationContext;
import dtd.PHS.VND_ExchangeRate.utils.Helpers;
import dtd.PHS.VND_ExchangeRate.utils.Logger;

public class UpdateRatesService 
	extends Service 
	implements Runnable {


	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		Logger.logInfo("Service created !");
		new Thread( this ).start();
	}
	
	@Override	
	public void run() {
		//parse data from internet
		//if not success: exit
		//if success: 
		//	- update db (Constraits: update memcache)
		//	- broadcast: update UI if needed	
		
		Logger.logInfo("Service running!");
		if ( ! Helpers.isConnectedToInternet() ) {
			//nothing
		} else {
			Logger.logInfo("Parser is starting ...");
			VCBRatesParser vcbParser = new VCBRatesParser();
			try {
				vcbParser.parse();
				VNExDatabase.refreshDB( vcbParser.getRates(),vcbParser.getDate() );
				broadcastUIUpdate();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				Logger.logError(e);
			}
		}	
		stopSelf();
		
	}

	//broadcast intent
	private void broadcastUIUpdate() {
		Intent i = new Intent();
		i.setAction(getApplicationContext().getString(R.string.UPDATE_RATE_BROADCAST_INTENT));
		ApplicationContext.getContext().sendBroadcast(i);
	}
}
